//
//  ChangePersonalInfoVC.m
//  Cunli
//
//  Created by lilubin on 15/6/30.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "ChangePersonalInfoVC.h"
#import "PersonalInfoCell.h"
#import "Config.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "User.h"
#import "ChangeNameVC.h"
#import "ChangeIDCardVC.h"
#import "ChangeSignaureVC.h"
#import "ChangeSexVC.h"
#import "ChangeWorkareaVC.h"
#import "ChangeCareerVC.h"
#import "ChangeBirthdayVC.h"
#import "PersonalPortraitCell.h"
#import "Utils.h"
#import "UIImage+MultiFormat.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "UIImage+fixOrientation.h"
#import "UIColor+expanded.h"
#import "User.h"

#define KCLPORTRAITCHANGE @"portraitChanged"

static NSString *kPersonalInfoCell = @"personalInfoCell";


@interface ChangePersonalInfoVC () <UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    NSDictionary *_userinfo;
    NSIndexPath *_oldSelIndexPath;
    UIImage *_imageToUpload;
}
@end

@implementation ChangePersonalInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavAttributes];
//    [self loadPersonalData];
    [self registerPersonlInfoCell];
    self.navigationItem.title = @"个人资料";
    self.tableView.sectionHeaderHeight = 2;
    self.tableView.sectionFooterHeight = 2;
    [self.tableView setBackgroundColor:[UIColor colorWithHexString:@"0xf6f6f6"]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(instancetype)init
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    return self;
}


- (void)setNavAttributes
{
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 28, 28);
    [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)registerPersonlInfoCell
{
    UINib *nib = [UINib nibWithNibName:@"PersonalInfoCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kPersonalInfoCell];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (_oldSelIndexPath != nil) {
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:_oldSelIndexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
}

#pragma mark - Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 80;
    }
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 15;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return 6;
    }
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSArray *titles = @[
                        @[@"姓名", @"性别", @"出生日期", @"身份证号", @"职业", @"现居住地"
                          ],
                        @[@"个性签名"]
                        ];
    NSArray *contentKeys =  @[
                              @[@"truename", @"sex", @"birthday", @"idcard", @"career", @"workareaname"
                                ],
                              @[@"signaure"]
                              ];
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"PersonalPortraitCell" owner:nil options:nil];
        PersonalPortraitCell *cell = nibs.lastObject;
        
        
//        if ([CLUser shareCLUser].pic.length != 0) {
//            cell.portraitURLStr = [CLUser shareCLUser].pic;
//        }
        
        if ([Login curLoginDetailUser].pic != nil) {
            cell.portraitURLStr = [Login curLoginDetailUser].pic;
        }
        
        return cell;
    }
    
    PersonalInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:kPersonalInfoCell forIndexPath:indexPath];
    
    cell.title = titles[indexPath.section - 1][indexPath.row];
    
//    NSString *contentKey = contentKeys[indexPath.section - 1][indexPath.row];
//    cell.content = [[CLUser shareCLUser] perform_string:contentKey];
    
    NSString *getContentKey = contentKeys[indexPath.section - 1][indexPath.row];
    if ([[Login curLoginDetailUser] respondsToSelector:NSSelectorFromString(getContentKey)]) {
        cell.content = [[Login curLoginDetailUser] performSelector:NSSelectorFromString(getContentKey)];
    }
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [self choseImageUpload];
        }
    }
    else if (indexPath.section == 1) {
        switch (indexPath.row) {
                /*
                 case 0:
                 {
                 [self choseImageUpload];
                 break;
                 }
                 */
            case 0:
            {
                ChangeNameVC *changeNameVC = [[ChangeNameVC alloc] init];
                [self.navigationController pushViewController:changeNameVC animated:YES];
                break;
            }
            case 1:
            {
                ChangeSexVC *sexVC = [[ChangeSexVC alloc] init];
                [self.navigationController pushViewController:sexVC animated:YES];
                break;
            }
            case 2:
            {
                ChangeBirthdayVC *birthdayVC = [[ChangeBirthdayVC alloc] init];
                [self.navigationController pushViewController:birthdayVC animated:YES];
                break;
            }
            case 3:
            {
                ChangeIDCardVC *changeIDCardVC = [[ChangeIDCardVC alloc] init];
                [self.navigationController pushViewController:changeIDCardVC animated:YES];
                break;
            }
            case 4:
            {
                ChangeCareerVC *careerVC = [[ChangeCareerVC alloc] init];
                [self.navigationController pushViewController:careerVC animated:YES];
                break;
            }
            case 5:
            {
                ChangeWorkareaVC *workareaVC = [[ChangeWorkareaVC alloc] init];
                [self.navigationController pushViewController:workareaVC animated:YES];
                break;
            }
            default:
                break;
        }
    }
    else if(indexPath.section == 2)
    {
        ChangeSignaureVC *signaureVC = [[ChangeSignaureVC alloc] init];
        [self.navigationController pushViewController:signaureVC animated:YES];
    }
    _oldSelIndexPath = indexPath;
}

#pragma - mark 选择本地图片上传
- (void)choseImageUpload
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"添加图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册中选择", nil];
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    /*
     buttonIndex:
     0:拍照
     1:相册
     2:取消
     */
#pragma mark - csdn example
    if (buttonIndex == actionSheet.cancelButtonIndex) {
        return;
    } else if (buttonIndex == 1) {
        UIImagePickerController *imagePickerController = [UIImagePickerController new];
        imagePickerController.delegate = self;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePickerController.allowsEditing = NO;
        imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
        
        [self presentViewController:imagePickerController animated:YES completion:nil];
    } else {
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"警告"
                                                                message:@"无法访问摄像头"
                                                               delegate:nil
                                                      cancelButtonTitle:@"取消"
                                                      otherButtonTitles: nil];
            
            [alertView show];
        } else {
            UIImagePickerController *imagePickerController = [UIImagePickerController new];
            imagePickerController.delegate = self;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickerController.allowsEditing = NO;
            imagePickerController.showsCameraControls = YES;
            imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
            
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
    }
    
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //    NSLog(@"didFinishPickingMediaWithInfo");
    [picker dismissViewControllerAnimated:YES completion:NULL];
    UIImage *img = info[UIImagePickerControllerOriginalImage];
    _imageToUpload = img;
#warning 此处是需要的，将头像图片保存在本地
//    [CLUser shareCLUser].portraitImage = img;
    [self uploadImage:img];
}

- (void)uploadImage:(UIImage *)image
{
    image = [image fixOrientation];
    //  image = [Utils sizeCompressImageWith:image];
    NSData *imageData = [Utils compressImage:image];
    //  NSLog(@"imageData.length:%lu", (unsigned long)imageData.length);
    
    /*
     if (imageData.length/512 > 512) {
     NSLog(@"execute imageCompress");
     image = [UIImage compressImageWith:image];
     imageData = [Utils compressImage:image];
     }
     */
    if (image.size.height > 128 && image.size.width > 128) {
        NSLog(@"execute imageCompress");
        image = [UIImage compressHeaderImageWith:image];
        imageData = [Utils compressImage:image];
    }
    
    NSString *imageEncodeStr = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    NSString *imageEncodeStr2 = [imageEncodeStr stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:3];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:imageEncodeStr2 forKey:@"file_name"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:@"upfile.php" httpMethod:@"POST" params:CheckParams fileDatas:nil complection:^(id result) {
        NSLog(@"In ChangePersonalInfoVC Upfile:%@", result);
        if ([result[@"response"] isEqualToString:@"upfile"]) {
//            [CLUser shareCLUser].pic = result[@"url"];
//            [Config saveUserPortraitURL:result[@"url"]];
            [Login curLoginDetailUser].pic = result[@"url"];
            dispatch_async(dispatch_get_main_queue(), ^{
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
            });
            [[NSNotificationCenter defaultCenter] postNotificationName:KCLPORTRAITCHANGE object:@YES];
        }
        else
        {
            NSDictionary *errorDic = result[@"error"];
            [Config showHUDWithText:errorDic[@"text"] andImage:@"error"];
            
        }
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
    }];
    
}

@end
